import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:video_player/video_player.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_share/mine_share_page.dart';
import 'package:tiktokadult/hj_page/video/view/detail_top_right_view.dart';
import '../../../hj_model/acg/comic_chapters_model.dart';
import '../../../hj_utils/api_service/mine_service.dart';
import '../../../hj_utils/global.dart';
import '../../../routers/jump_router.dart';
import '../../../tools_base/debug_log.dart';
import '../../../tools_base/global_store/store.dart';
import '../../../tools_base/loading/loading_alert_widget.dart';
import '../../../tools_base/net/api_exception.dart';
import '../../../tools_base/net/base_resp_bean.dart';

class VideoMaskBuyView extends StatefulWidget {
  final VideoModel? model;
  final VideoPlayerController? videoPlayerController;
  final Function? callback;

  VideoMaskBuyView(
    this.model, {
    this.videoPlayerController,
    this.callback,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoMaskBuyViewState();
  }
}

class _VideoMaskBuyViewState extends State<VideoMaskBuyView> {
  LongVideStatus get status => longVideoStatusDesc(widget.model);

  bool get isNeedVip => status.isNeedVip;

  bool get isNeedBuy => status.isNeedBuy;

  bool get isCartoon => widget.model?.videoType == 1;
  bool isBuying = false;

  bool get isUpStyle => widget.model?.recoFlag == 2;

  String get leftBtTitle {
    if (isUpStyle) {
      return "金币充值";
    }
    return isNeedBuy ? "${widget.model?.coins}金币解锁" : "分享得VIP";
  }

  String get rightBtTitle {
    if (isUpStyle) {
      return "立即订阅";
    }
    return "立即开通VIP";
  }

  ///购买作品
  void _buyProduct() async {
    if (isBuying) return;
    isBuying = true;
    setState(() {});
    try {
      String? productID = widget.model?.id;
      int productType = 1;
      if (widget.model?.videoType == 1) {
        productType = 19;
        productID = widget.model?.mediaInfo?.id;
      }
      LoadingAlertWidget.show();
      BaseRespBean data = await MineService.postBuyVideo(productID, productType);
      LoadingAlertWidget.cancel();
      if (data.isSuccess) {
        widget.model?.vidStatus?.hasPaid = true;
        widget.model?.mediaInfo?.mediaStatus?.hasPaid = true;
        widget.videoPlayerController?.play();
        globalStore.updateUserInfo();
        widget.callback?.call();
      } else {
        if (data.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast("网络异常, 支付失败");
        }
      }
    } on DioException catch (e) {
      LoadingAlertWidget.cancel();
      var error = e.error;
      if (error is ApiException) {
        if (error.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast(error.message);
        }
      } else {
        showToast(e.toString());
      }
      debugLog('productBuy', e.toString());
    } catch (e) {
      LoadingAlertWidget.cancel();
      debugLog('postBuyVideo', e.toString());
    }
    isBuying = false;
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (isNeedBuy || isNeedVip) {
      String titleDesc = "试看结束";
      if (isUpStyle) {
        titleDesc = "订阅该UP主";
      }
      return GestureDetector(
        child: Container(
          alignment: Alignment.center,
          color: Color.fromRGBO(0, 7, 18, 0.8),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                titleDesc,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              12.sizeBoxH,
              Text(
                isUpStyle ? "即可免费观看所有专属视频" : "开通VIP 永久免费观看",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () {
                      if (isUpStyle) {
                        jumpToWalletPage(tabPosition: 1);
                      } else if (isNeedBuy) {
                        _buyProduct();
                      } else {
                        Get.to(() => MineSharePage(), preventDuplicates: false);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 5),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                          Color(0xffFD9E4A),
                          Color(0xffFD9E4A),
                        ]),
                        borderRadius: BorderRadius.circular(3),
                      ),
                      child: Text(
                        leftBtTitle,
                        style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                  SizedBox(width: 18),
                  GestureDetector(
                    onTap: () async {
                      if (isUpStyle) {
                      } else {
                        jumpToWalletPage();
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 5),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                          Color(0xffFE3653),
                          Color(0xffFE3653),
                        ]),
                        borderRadius: BorderRadius.circular(3),
                      ),
                      child: Text(
                        rightBtTitle,
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      );
    } else {
      return SizedBox();
    }
  }
}
